package com.JackTang.fruit.controllers;

import com.JackTang.fruit.service.FruitService;
import com.JackTang.fruit.service.impl.FruitServiceImpl;
import com.JackTang.fruit.pojo.Fruit;
import com.myssm.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author Jack Tang
 * @description
 * @create 2023-05-07 15:55
 */

public class FruitController{

    private FruitService fruitService = null;


    private String index(String oper, String keyword, Integer pageNo, HttpServletRequest req){

        // 将 pageNo 保存到session作用域中
        HttpSession session = req.getSession();

        if (pageNo == null){
            pageNo = 1;
        }

        if (StringUtil.isNotEmpty(oper) && "search".equals(oper)){
            pageNo = 1;
            if (StringUtil.isEmpty(keyword)) {
                keyword = "";
            }
            session.setAttribute("keyword",keyword);
        }else {

            Object keywordObj = session.getAttribute("keyword");
            if (keywordObj != null){
                keyword = (String) keywordObj;
            }else {
                keyword = "";
            }

        }

        // 重新更新 pageNo 的值
        session.setAttribute("pageNo",pageNo);

        List<Fruit> fruitList = fruitService.getFruitList(keyword, pageNo);
        session.setAttribute("fruitList",fruitList);

        int pageEnd = fruitService.getPageCount(keyword);
        session.setAttribute("pageEnd",pageEnd);

        //super.processTemplate("index",req,resp);
        return "index" ;

    }

    private String add(String fname, Integer price, Integer fcount, String remark) {

        fruitService.addFruit(new Fruit(0,fname,price,fcount,remark));

        return "redirect:fruit.do";
    }

    private String del(Integer fid){
        if (fid != null){
            fruitService.delFruit(fid);
            return "redirect:fruit.do";
        }
        return "error" ;
    }

    private String edit(Integer fid, HttpServletRequest req){
        if (fid != null){
            Fruit fruit = fruitService.getFruitById(fid);
            req.setAttribute("fruit",fruit);
            //super.processTemplate("edit",req,resp);
            return "edit";
        }
        return "error";
    }

    private String update(Integer fid, String fname, Integer price, Integer fcount, String remark) {

        // 更新
        fruitService.updateFruit(new Fruit(fid,fname,price,fcount,remark));

        // 资源跳转
        //resp.sendRedirect("fruit.do");
        return "redirect:fruit.do";
    }
}